<template>
  <MrCustom bg-color="bg-gradual-blue " is-back>
    <template #backText>
      返回
    </template>
    <template #content>
      {{articleInfo.title}}
    </template>
  </MrCustom>
  <view v-if="articleInfo">
    <view :style="{paddingBottom: iphoneXBottomH + 'px'}">
      <view class="bg-white flex justify-between solids-bottom margin-bottom padding-xs align-center">
        <view class="flex flex-sub  align-center">
          <view :style="'color:'+getArticleStatusColor(articleInfo.status)" class="cuIcon-title"></view>
          <view>{{ getArticleStatus(articleInfo.status) }}</view>
        </view>
        <button v-if="isEdit" class="cu-btn bg-red margin-left" @click="handleRemove">删除</button>
        <button v-if="articleInfo.status===1||articleInfo.status===2" class="cu-btn bg-cyan margin-left"
                @click="handleCancel">下架
        </button>
        <button v-if="(isEdit&&articleInfo.status===0)||articleInfo.status===3" class="cu-btn bg-yellow margin-left"
                @click="handlePublish">发布
        </button>
        <button class="cu-btn bg-green margin-left" @click="handleSubmit">保存</button>
      </view>
      <view class="solids-bottom">
        <uni-forms ref="formRef" :rules="rules" :modelValue="formData">
          <uni-forms-item name="title" style="margin: 0">
            <view class=" solid">
              <view class="cu-form-group">
                <view class="title">标题</view>
                <input v-model="formData.title" placeholder="请输入文章标题" name="input"/>
              </view>
            </view>
          </uni-forms-item>
          <uni-forms-item>
            <view class=" solid">
              <view class="cu-form-group">
                <view class="title">分类</view>
                <input v-model="formData.type" placeholder="请输入文章分类" name="input"/>
              </view>
            </view>
          </uni-forms-item>
          <uni-forms-item>
            <view class=" solid">
              <view class="cu-form-group">
                <view class="title">封面</view>
                <view class="grid col-4 grid-square flex-sub padding-top">
                  <view v-if="!formData.coverImage" class="solids" @tap="chooseImage">
                    <text class='cuIcon-cameraadd'></text>
                  </view>
                  <view v-else class="bg-img">
                    <image :src="prefix+formData.coverImage" mode="aspectFill"></image>
                    <view class="cu-tag bg-red" @click="delImage">
                      <text class='cuIcon-close'></text>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </uni-forms-item>
          <uni-forms-item>
            <view class=" solid">
              <view class="cu-form-group">
                <view class="title">文本</view>
                <button class="cu-btn bg-blue" @click="toEditor">编辑</button>
              </view>
            </view>
          </uni-forms-item>
        </uni-forms>
      </view>
      <view class="bg-white padding radius-lg margin">
        <view class="text-break-all" v-html="formData.content"></view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">


import {ref, watch} from "vue";
import {onLoad, onUnload} from "@dcloudio/uni-app";
import UniForms from "@/uni_modules/uni-forms/components/uni-forms/uni-forms.vue";
import UniFormsItem from "@/uni_modules/uni-forms/components/uni-forms-item/uni-forms-item.vue";
import api from "@/api";
import {debounce, getArticleStatus, getArticleStatusColor} from "@/utils";
import {imagePathPrefix,uploadFile} from '/settings'
import MrCustom from "@/components/common/MrCustom.vue";

const prefix = imagePathPrefix
const url=uploadFile.url
const name=uploadFile.name

const isEdit = ref(false)
const iphoneXBottomH = ref(0)
const formRef = ref()
const rules = ref()
const formData = ref({
  coverImage: '',
  title: '',
  content: '',
  type: '',
})
const oldFormData = ref()
const nurseInfo = ref()
const isSave = ref(true)
const articleInfo = ref({
  status: 0,
})

watch((formData.value), debounce(() => {
  if (JSON.stringify(formData.value) !== JSON.stringify(oldFormData.value)) {
    console.log('提示')
    uni.enableAlertBeforeUnload({
      message: "当前编辑未保存，是否退出"
    })
  }
}, 500))

const chooseImage = () => {
  uni.chooseImage({
    count: 4, //默认9
    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album'], //从相册选择
    success: (res) => {
      uni.uploadFile({
        url: url, //仅为示例，非真实的接口地址
        filePath: res.tempFilePaths[0],
        name: name,
        success: (uploadFileRes) => {
          let tmp = JSON.parse(uploadFileRes.data).data
          formData.value.coverImage = tmp
        }
      });
    }
  });
}
const delImage = () => {
  uni.showModal({
    title: '提示',
    content: '确定要删除这张图片吗？',
    cancelText: '取消',
    confirmText: '确认',
    success: res => {
      if (res.confirm) {
        formData.value.coverImage = ''
      }
    }
  })
}

onLoad((option) => {
  uni.disableAlertBeforeUnload()
  api.nurse.info({}).then(res => {
    if (res && res.data.code === 0) {
      if (res.data.data !== null) {
        nurseInfo.value = res.data.data
      } else {
        uni.navigateTo({
          url: '/pages/nurse/info/create',
          success: () => {
            uni.showToast({
              title: '请先完善信息',
              icon: 'error'
            })
          }
        })
      }
    }
  })
  if (option.articleInfo) {
    articleInfo.value = JSON.parse(decodeURIComponent(option.articleInfo))
    formData.value.title = articleInfo.value.title
    formData.value.content = articleInfo.value.content
    formData.value.type = articleInfo.value.type
    formData.value.coverImage = articleInfo.value.coverImage
    oldFormData.value = JSON.parse(JSON.stringify(formData.value))
    isEdit.value = true
  } else {
    isEdit.value = false
  }
})

onUnload(() => {
  uni.$off('save')
  let pages = getCurrentPages()
  let prePage = pages[pages.length - 2] //上一个页面
  if (prePage.route === 'pages/nurse/article/index') {
    prePage.$vm.myArticleReload()
  }

})
const toEditor = () => {
  uni.navigateTo({
    url: '/pages/nurse/article/edit?content=' + encodeURIComponent(JSON.stringify( formData.value.content))
  })
  uni.$on('save', res => { //开启监听保存事件
    formData.value.content = res.html
  })
}


const handleRemove = () => {
  uni.showModal({
    title: '提示',
    content: '确认要删除？',
    confirmText: "确认",
    cancelText: "取消",
    success: (res) => {
      if (res.confirm) {
        api.article.remove({
          id: articleInfo.value.id
        }).then(res => {
          if (res && res.data.code === 0) {
            uni.disableAlertBeforeUnload()
            articleInfo.value.status = 0
            uni.navigateBack({
              success: () => {
                uni.showToast({
                  title: res.data.msg,
                  icon: 'success',
                })
              }
            })
          }
        })
      }
    }
  })
}

/**
 * 下架
 */
const handleCancel = () => {
  if (JSON.stringify(formData.value) !== JSON.stringify(oldFormData.value)) {
    uni.showToast({
      title: '请先保存',
      icon: 'error'
    })
  } else {
    uni.showModal({
      title: '提示',
      content: '确认要下架？',
      confirmText: "确认",
      cancelText: "取消",
      success: (res) => {
        if (res.confirm) {
          api.article.cancel({
            id: articleInfo.value.id
          }).then(res => {
            if (res && res.data.code === 0) {
              articleInfo.value.status = 0
              uni.showToast({
                title: res.data.msg,
                icon: 'success',
              })
            }
          })
        }
      }
    })
  }


}

const handlePublish = () => {
  if (JSON.stringify(formData.value) !== JSON.stringify(oldFormData.value)) {
    uni.showToast({
      title: '请先保存',
      icon: 'error'
    })
  } else {
    uni.showModal({
      title: '提示',
      content: '确认要发布？',
      confirmText: "确认",
      cancelText: "取消",
      success: (res) => {
        if (res.confirm) {
          api.article.publish({
            id: articleInfo.value.id
          }).then(res => {
            if (res && res.data.code === 0) {
              articleInfo.value.status = 1
              uni.showToast({
                title: res.data.msg,
                icon: 'success',
              })
            }
          })
        }
      }
    })
  }
}

const handleSubmit = () => {
  if (isEdit.value) {
    api.article.update({
      id: articleInfo.value.id,
      type: formData.value.type,
      title: formData.value.title,
      content: formData.value.content,
      coverImage: formData.value.coverImage,
    }).then(res => {
      if (res && res.data.code === 0) {
        oldFormData.value = JSON.parse(JSON.stringify(formData.value))
        uni.disableAlertBeforeUnload()
        uni.showToast({
          title: res.data.msg,
          icon: 'success',
        })
      }
    })
  } else {
    api.article.create({
      type: formData.value.type,
      username: nurseInfo.value.username,
      avatar: nurseInfo.value.avatar,
      name: nurseInfo.value.name,
      title: formData.value.title,
      content: formData.value.content,
      coverImage: formData.value.coverImage,
    }).then(res => {
      if (res && res.data.code === 0) {
        oldFormData.value = JSON.parse(JSON.stringify(formData.value))
        uni.disableAlertBeforeUnload()
        isEdit.value = true
        uni.showToast({
          title: res.data.msg,
          icon: 'success',
        })
      }
    })
  }
}
</script>

<style scoped>
/deep/ .uni-forms-item {
  margin-bottom: 0;
}
</style>